package com.mmall.mmall002.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mmall.mmall002.entity.Cart;
import com.mmall.mmall002.entity.Product;
import com.mmall.mmall002.enums.ResultEnum;
import com.mmall.mmall002.exception.MmallException;
import com.mmall.mmall002.mapper.CartMapper;
import com.mmall.mmall002.mapper.ProductMapper;
import com.mmall.mmall002.service.CartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mmall.mmall002.vo.CartVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 龙菲
 * @since 2021-03-02
 */
@Service
@Slf4j
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public boolean save(Cart entity) {
        //扣除库存
        Product product = productMapper.selectById(entity.getProductId());

        Integer stock = product.getStock() - entity.getQuantity();

        if(stock < 0){
            log.error("[添加购物车 ，库存不足! stock={}]",stock);
            throw new MmallException(ResultEnum.STOCK_ERROR);
        }
        product.setStock(stock);

        productMapper.updateById(product);

        if(cartMapper.insert(entity) == 1){
            return true;
        }
        return false;
    }

    /**
     * 根据用户编号查找购物车信息
     * @param userId
     * @return
     */
    @Override
    public List<CartVO> findAllCartVOByUserId(Integer userId) {

        List<CartVO> cartVOList = new ArrayList<>();

        //根据userId 查询cart购物车集合
        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_id",userId);
        List<Cart> cartList = cartMapper.selectList(qw);

        for (Cart cart : cartList) {
            CartVO cartVO = new CartVO();


            //获得商品对象
            Product product = productMapper.selectById(cart.getProductId());
//            cartVO.setProductId(product.getId());
            BeanUtils.copyProperties(product,cartVO);

            BeanUtils.copyProperties(cart,cartVO);

            //添加到购物车的VO集合
            cartVOList.add(cartVO);
        }
        return cartVOList;
    }


}
